<style>
.text {
  font-size: 16px;
}

.clearfix{
  background-color: #F9F9F9;
  color: #666666;
  font-weight: bold;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both
}
.el-card__header{
  background-color: #F9F9F9;
}
.box-card {
  width: 100%;
  margin: auto;
  margin-bottom: 10px;
}
.foot{
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  position: fixed;
  bottom: 0;
  background-color: #fff;
  width: calc(100vw - 200px);
  right: 0;
}
.app-container{
  position: relative;
}

.el-table__header-wrapper .el-checkbox {
  display: none;
}
</style>
<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>采集设置</span>
      </div>
      <div class="text item">
        <el-form :model="queryParams" ref="queryForm" size="small" v-show="showSearch" label-width="68px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="采集方式">
                <el-radio v-model="cjfs" label="1">类目采集</el-radio>
                <el-radio v-model="cjfs" label="2">关键词采集</el-radio>
                <el-radio v-model="cjfs" label="3">爆款采集</el-radio>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11" style="margin-right: 10px;">
              <el-form-item label="类目">
                <el-cascader-panel
                  class="tree-border"
                  :options="categoryOptions"
                  @change="handCascaderChange"
                  show-checkbox
                  ref="menu"
                  :props="{ multiple: true}"
                  node-key="id"
                  empty-text="加载中，请稍候"
                  v-model="selectedOptions"
                ></el-cascader-panel>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="价格区间">
                <el-input
                  style="width: 100px"
                  v-model="queryParams.priceStart"
                  placeholder="请输入最小价格"
                  type="number"
                  @keyup.enter.native="handleQuery"
                />
                <span style="width: 10%;"> - </span>
                <el-input
                  style="width: 100px"
                  v-model="queryParams.priceEnd"
                  placeholder="请输入最大价格"
                  type="number"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="佣金率%" prop="">
                <el-input
                  style="width: 100px"
                  v-model="queryParams.commissionRateStart"
                  placeholder="请输入最小佣金率"
                  type="number"
                  @keyup.enter.native="handleQuery"
                />
                <span style="width: 10%;"> - </span>
                <el-input
                  style="width: 100px;"
                  v-model="queryParams.commissionRateEnd"
                  placeholder="请输入最大佣金率"
                  type="number"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="付款人数" prop="">
                <el-input
                  style="width: 100px"
                  v-model="queryParams.payersStart"
                  placeholder="请输入最小付款人数"
                  type="number"
                  @keyup.enter.native="handleQuery"
                />
                <span style="width: 10%;"> - </span>
                <el-input
                  style="width: 100px"
                  v-model="queryParams.payersEnd"
                  placeholder="请输入最大付款人数"
                  type="number"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="佣金区间" prop="">
                <el-input
                  style="width: 100px"
                  v-model="queryParams.commissionStart"
                  placeholder="请输入最小佣金"
                  type="number"
                  @keyup.enter.native="handleQuery"
                />
                <span style="width: 20px"> - </span>
                <el-input
                  style="width: 100px;"
                  v-model="queryParams.commissionEnd"
                  placeholder="请输入最大佣金"
                  type="number"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="过滤专向链接" label-width="width: 96px;">
                <el-checkbox v-model="iszx"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="库存区间">
                <el-input
                  style="width: 100px"
                  v-model="queryParams.stockStart"
                  placeholder="请输入最小库存"
                  type="number"
                  @keyup.enter.native="handleQuery"
                />
                <span style="width: 10%;"> - </span>
                <el-input
                  style="width: 100px"
                  v-model="queryParams.stockEnd"
                  placeholder="请输入最大库存"
                  type="number"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="过滤三方平台未收录" label-width="width: 96px;">
                <el-checkbox v-model="isxj"/>
              </el-form-item>
            </el-col>
            <el-col :span="6" >

                <el-form-item label="排序条件" prop="orderBys">
                  <el-select
                    v-model="queryParams.orderBys"
                    placeholder="排序条件"
                    style="width: 200px"
                  >
                    <el-option
                      v-for="dict in dict.type.sys_orderbys"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="排序顺序" prop="orderSet">
                  <el-select
                    v-model="queryParams.orderSet"
                    placeholder="排序顺序"
                    style="width: 200px"
                  >
                    <el-option key="desc" label="倒序" value="desc"/>
                    <el-option key="asc" label="正序" value="asc"/>
                  </el-select>
                </el-form-item>
              </el-col>
          </el-row>
          <el-row>
            <el-col :span="11">
              <el-form-item label-width="68px" label="关键词">
                <el-input v-model="titleWords" :rows="5" type="textarea" placeholder="请输入内容,一行一个词"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label-width="68px" label="违规词">
                <el-input v-model="sensitiveWords" :rows="5" type="textarea" placeholder="请输入内容,一行一个词"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>

          </el-row>

          <el-row>
            <el-col :span="24" style="text-align: center">
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" :disabled="isDis" size="mini" @click="handleQuery">开始采集</el-button>
                <el-button icon="el-icon-refresh" type="danger" size="mini" :disabled="!isDis"  @click="stopcj">停止采集</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-card>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          :disabled="isDis"
          v-hasPermi="['system:dygoods:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-close"
          size="mini"
          @click="handleClear"
          :disabled="isDis"
          v-hasPermi="['system:dygoods:export']"
        >清空</el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="danger"-->
      <!--          plain-->
      <!--          icon="el-icon-delete"-->
      <!--          size="mini"-->
      <!--          @click="handleSync"-->
      <!--          v-hasPermi="['system:goods:sync']"-->
      <!--        >数据同步</el-button>-->
      <!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          @click="handleES"-->
<!--          v-hasPermi="['system:goods:sync']"-->
<!--        >同步缓存</el-button>-->
<!--      </el-col>-->
      <sapn style="float: right;margin-right: 10px;">采集数量:{{num}}</sapn>
    </el-row>
      <el-table row-key="id"
                v-loading="loading"
                border
                height="350px"
                ref="myTable"
                class="fixed-width"
                :data="visibleGoodsList">
        <el-table-column label="序号" width="80" type="index" align="center"></el-table-column>
        <!--      <el-table-column label="抖音商品主键" width="100" align="center" :v-show="false" prop="id" show-overflow-tooltip/>-->
        <el-table-column label="抖音商品id" width="180" align="center" prop="product_id" show-overflow-tooltip/>
        <el-table-column label="分类名称" width="80" align="center" prop="category_name" show-overflow-tooltip/>
        <el-table-column label="标题"  width="330" align="center" prop="title" show-overflow-tooltip/>
        <!--      <el-table-column label="封面链接" width="80" align="center" prop="cover" show-overflow-tooltip/>-->
        <el-table-column label="价格" align="center" width="80" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ (scope.row.price / 100).toFixed(2) }}</span>
          </template>
        </el-table-column>

        <!--      <el-table-column label="状态" align="center" prop="status" show-overflow-tooltip/>-->
        <!--      <el-table-column label="添加时间" width="80" align="center" prop="addTime" show-overflow-tooltip/>-->
        <!--      <el-table-column label="更新时间" width="80" align="center" prop="upTime" show-overflow-tooltip/>-->
        <el-table-column label="店铺名称" width="120" align="center" prop="shop_name" show-overflow-tooltip/>
        <!--      <el-table-column label="评论数" align="center" prop="comment_num" show-overflow-tooltip/>-->
        <!--      <el-table-column label="评分" align="center" prop="comment_score" show-overflow-tooltip />-->
        <el-table-column label="库存数" width="90" align="center" prop="product_stock" show-overflow-tooltip/>
        <el-table-column label="佣金比率" width="90" align="center" prop="activity_cos_ratio" show-overflow-tooltip />
        <el-table-column label="佣金" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{(scope.row.activity_cos_ratio / 10000 * scope.row.price).toFixed(2) }}</span>
          </template>
        </el-table-column>
<!--        <el-table-column label="带货达人数" align="center" prop="kol_num" show-overflow-tooltip/>-->
<!--        <el-table-column label="状态" align="center" prop="status" show-overflow-tooltip/>-->
        <el-table-column label="销量" align="center" prop="sales" show-overflow-tooltip/>
        <!--      <el-table-column label="详情页链接" width="90" align="center" prop="detail_url" show-overflow-tooltip/>-->
        <!--      <el-table-column label="订单量" align="center" prop="order_num" show-overflow-tooltip/>-->
        <!--      <el-table-column label="店铺id" align="center" prop="shop_id" show-overflow-tooltip/>-->
        <!--      <el-table-column label="专向链接" align="center" prop="is_assured" show-overflow-tooltip/>-->
        <!--      <el-table-column label="两小时销量" width="90" align="center" prop="twohour" show-overflow-tooltip/>-->
        <!--      <el-table-column label="日销量" align="center" prop="oneday" show-overflow-tooltip/>-->
        <!--      <el-table-column label="周销量" align="center" prop="week" show-overflow-tooltip/>-->
        <!--      <el-table-column label="月销量" align="center" prop="month" show-overflow-tooltip/>-->
        <!--      <el-table-column label="原始价格" align="center" prop="origin_price" show-overflow-tooltip/>-->
        <!--      <el-table-column label="产品库存" align="center" prop="product_stock" show-overflow-tooltip/>-->
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :current-page="currentPage"
        :page.sync="currentPage"
        :limit.sync="queryParams.pageSize"
        @pagination="updateVisibleGoodsList"
      />
  </div>
</template>

<script>
import { listGoods, getGoods, delGoods, addGoods, updateGoods ,syncDyGoods,esDyGoods,stopList,findState} from "@/api/system/goods";
import {treeselect} from "@/api/system/category";
import VirtualScroll from 'el-table-virtual-scroll'
import { saveAs } from 'file-saver';

export default {
  name: "Goods",
  dicts: ['sys_orderbys'],
  component: {
    VirtualScroll
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      isDis:false,
      num:0,
      // 总条数
      total: 0,
      // 抖音商品表格数据
      goodsList: [],
      visibleGoodsList: [],
      selectedOptions:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        priceStart:0,
        priceEnd:999999,
        payersStart:0,
        payersEnd:999999,
        commissionStart:0,
        commissionEnd:100,
        commissionRateStart:0,
        commissionRateEnd:100,
        orderSet:"desc",
        stockStart:0,
        stockEnd:999999,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        productId: [
          { required: true, message: "抖音商品id不能为空", trigger: "blur" }
        ],
      },
      categoryOptions:[],
      titleWords:"",
      iszx: true,
      isxj: true,
      isbk: true,
      cjfs: "1",
      sensitiveWords:"",
      isStart: false,
      pageSize: 10,         // 每页显示的商品数量
      currentPage: 1,       // 当前页码
    };
  },
  created() {
    this.getCategoryTreeselect();
    //this.findstate();
  },
  methods: {
    /** 查询抖音商品列表 */
    async getList() {
      try {
        const response = await listGoods(this.queryParams);
        const data = response.rows;
        if(data.length==0){
          this.$modal.msgError("没有采取到相关数据！");
          this.isStart = false;
          this.isDis = false;
          this.loading = false;
          this.num = "0";
          return;
        }
        let index = 0;
        const delay = 200; // 延时时间（毫秒）

        const addData = () => {
          if (index < data.length && this.isStart) {
            this.goodsList.push(data[index]);
            if(this.visibleGoodsList.length<10){
              this.visibleGoodsList.push(data[index]);
            }
            // this.num++;
            this.total = this.num;
            index++;
            setTimeout(addData, delay); // 延时执行添加数据
          }
          // else {
          //   // 所有数据添加完成后执行下一次 getList
          //   if (this.isStart) {
          //     this.queryParams.pageNum += 1;
          //     this.getList(); // 递归调用 getList
          //   }
          // }
        };

        addData(); // 开始添加数据

      } catch (error) {
        this.isDis = false;
        this.isStart = false;
        this.loading = false;
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        productId: null,
        categoryId: null,
        categoryName: null,
        title: null,
        cover: null,
        price: null,
        status: null,
        addTime: null,
        upTime: null,
        labelIds: null,
        shopName: null,
        commentNum: null,
        commentScore: null,
        couponPrice: null,
        inStock: null,
        kolNum: null,
        sales: null,
        hasSxt: null,
        detailUrl: null,
        orderNum: null,
        firstCid: null,
        secondCid: null,
        shopId: null,
        thirdCid: null,
        isAssured: null,
        twohour: null,
        oneday: null,
        week: null,
        month: null,
        activityCosRatio: null,
        corpId: null,
        promotionStartTime: null,
        promotionEndTime: null,
        originPrice: null,
        productStock: null,
        createTime: null,
        createBy: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.goodsList = [];
      this.visibleGoodsList = [];
      this.total = 0;
      var strings = this.sensitiveWords.split(/\r?\n/);
      var titles = this.titleWords.split(/\r?\n/);
       this.queryParams.categoryList = this.getCategoryAllCheckedKeys();
      // if(this.queryParams.categoryList.length==0 && (titles.length==1 && titles[0] == "")){
      //   this.$modal.msgWarning("请选择关键词采集,或者类目采集！");
      //   return false;
      // }
      //类目采集
      if(this.cjfs == 1){
        if( this.queryParams.categoryList.length==0){
          this.$modal.msgWarning("请选择类目！");
          return false;
        }
      }
      //关键词采集
      if(this.cjfs == 2){
        if(titles.length==1 && titles[0] == ""){
          this.$modal.msgWarning("请输入关键词！");
          return false;
        }
      }
      //爆款采集
      if(this.cjfs == 3){
        if(this.queryParams.categoryList.length==0){
          this.$modal.msgWarning("请选择类目进行爆款采集！");
          return false;
        }
      }
      this.queryParams.pageNum = 1;
      this.queryParams.sensitiveWords = strings;
      this.queryParams.titlesWords = titles;
      this.queryParams.iszx = this.iszx == true ? 0:1;
      this.queryParams.isbk = this.cjfs == 3? 1:0;
      this.isStart = true;
      this.isDis = true;
      this.num = '采集中...';
      this.loading = true;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加抖音商品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getGoods(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改抖音商品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateGoods(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGoods(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除抖音商品编号为"' + ids + '"的数据项？').then(function() {
        return delGoods(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 数据同步按钮操作 */
    handleSync() {
      this.$modal.confirm('是否开始同步抖音商品吗？').then(function() {
        return syncDyGoods();
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("同步成功！");
      }).catch(() => {});
    },
    /** 数据同步按钮操作 */
    handleES() {
      this.$modal.confirm('是否开始同步抖音商品缓存吗？').then(function() {
        return esDyGoods();
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("同步成功！");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport(row) {
      // var ids = [];
      // console.log(ids)
      // if(ids==="" || ids.length==0){
      //   for(var i=0;i<this.goodsList.length;i++){
      //     ids.push(this.goodsList[i].id)
      //   }
      // }
      // this.download('system/dygoods/export', {
      //   ids:ids.join(",")
      // }, `信息采集_${new Date().getTime()}.txt`)

      const fileContent = this.goodsList.map(item => 'https://haohuo.jinritemai.com/ecommerce/trade/detail/index.html?id=' + item.product_id).join('\n');

      // 创建 Blob 对象
      const blob = new Blob([fileContent], { type: 'text/plain;charset=utf-8' });

      // 使用 FileSaver.js 保存文件
      saveAs(blob, '采集数据.txt');
    },
    /** 查询菜单树结构 */
    getCategoryTreeselect() {
      treeselect().then(response => {
        this.categoryOptions = response.data;
        this.findstate();
      });
    },
    // 所有菜单节点数据
    getCategoryAllCheckedKeys() {
      // 目前被选中的菜单节点
      debugger
      let checkedKeys = this.$refs.menu.getCheckedNodes();
      var data = [];
      if(checkedKeys.length>0){
        for(var i=0;i<checkedKeys.length;i++){
          data.push(checkedKeys[i].data.buId);
        }
      }
      return data;
    },
    //停止采集
    stopcj(){
      stopList().then(response =>{
        this.goodsList = [];
        const data = response.rows;
        this.goodsList.push(...data);
        if(this.visibleGoodsList.length<10){
          for(var i=0;i<10;i++){
            this.visibleGoodsList.push(data[i]);
          }
        }
        this.num = this.goodsList.length;
        this.total = this.goodsList.length;
        this.isStart = false;
        this.isDis = false;
        this.loading = false;
      })
    },
    //查询采集状态
    findstate(){
      findState().then(response =>{
        if(response.data != null){
          this.queryParams = response.data;
          this.queryParams.iszx == 1 ? this.queryParams.iszx = true :this.queryParams.iszx = false;
          this.queryParams.isbk == 1 ? this.queryParams.isbk = true: this.queryParams.isbk = false;
          this.queryParams.isxj == 1 ? this.queryParams.isxj = true: this.queryParams.isxj = false;
          this.isDis = true;
          this.loading = true;
          this.num = "采集中..."
          if(this.queryParams.categoryListString!=null){
            this.selectedOptions = this.queryParams.categoryListString.split("#");
            var list = [];
            for(var i=0;i<this.selectedOptions.length;i++){
              if(this.selectedOptions[i] != ""){
               var pnodes = this.findParentNode(this.categoryOptions,this.selectedOptions[i]);
                list.push(pnodes);
              }
            }
            console.log(list)
            this.selectedOptions = list;
          }
          if(this.queryParams.sensitiveWordsString!=null){
            this.sensitiveWords = this.queryParams.sensitiveWordsString.replace(/#/g, '\n');
          }
          if(this.queryParams.titlesWordsString!=null){
            this.titleWords = this.queryParams.titlesWordsString.replace(/#/g, '\n');
          }
        }
      })
    },
    handleClear(){
      this.goodsList = [];
      this.num = 0;
    },
    updateVisibleGoodsList() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.visibleGoodsList = this.goodsList.slice(start, end);
    },
    findParentNode(object, value) {
      for (var key in object) {
        if (object[key].buId == value) return [object[key].id];
        if(object[key].children && Object.keys(object[key].children).length > 0){
          var temp = this.findParentNode(object[key].children, value);
          if (temp) return [object[key].id, temp].flat();
        }
      };
    },
    handCascaderChange(val){
      console.log(val)
      // 单选（multiple=false） 时， val = ["zhinan","shejiyuanze","yizhi"]
      // 多选（multiple=true） 时， val = [["zhinan","shejiyuanze","yizhi"]]
    },
  }

};
</script>
